<?php

  require_once "JooS/Server/Resource/DataText.php";
  require_once "JooS/Server/Resource/DataElement.php";

  class JooS_Server_Resource extends JooS_Server_Resource_DataElement implements Serializable {
    const ROOT_ELEMENT = "rml";
    const DATA_ELEMENT = "resource";
    const REQUEST_ELEMENT = "request";

    private $_controller = null;

    public function __construct($data = null, JooS_Server_Controller $controller = null) {
      parent::__construct(self::ROOT_ELEMENT);

      $this["version"] = "1.0";

      if (!is_null($controller)) {
        $request = $controller->getRequest();

        $this["output"] = $request->getResourcePresentation();
        $this["role"] = $controller->getRoler()->get();

        $this->__set(self::REQUEST_ELEMENT, $request->getRequest());

        $requestElement = $this->__get(self::REQUEST_ELEMENT);
        $requestElement["path"] = $request->getResourcePath();
        $requestElement["action"] = $request->getResourceAction();

        $this->setController($controller);
      }

      $this->__set(self::DATA_ELEMENT, $data);
    }

    public function setController(JooS_Server_Controller $controller) {
      $this->_controller = $controller;
      return $this;
    }

    public function getController() {
      return $this->_controller;
    }

    public function getData() {
      return $this->nodeValue;
    }

    public function serialize() {
      return serialize($this->getData());
    }

    private function traverseUnserializedData($data, $childNodes) {
      if (isset($data[1])) {
        $firstChildIdx = is_object($data[1]) ? 2 : 1;
        
        if (is_array($data[1]) || is_object($data[1])) {
          $child = new JooS_Server_Resource_DataElement($data[0]);
          $childNodes[$data[0]] = $child;

          for ($i = $firstChildIdx; $i < sizeof($data); $i++) {
            $this->traverseUnserializedData($data[$i], $child->childNodes);
          }
        }
        else {
          $child = new JooS_Server_Resource_DataText($data[0], $data[$firstChildIdx]);
        }

        if (is_object($data[1]))
          foreach ($data[1] as $k => $v)
            $child[$k] = $v;

        $childNodes[$data[0]] = $child;
      }
    }

    public function unserialize($serialized) {
      $data = unserialize($serialized);
      $this->__construct($data[0]);

      $childIndex = is_object($data[1]) ? 2 : 1;
      for ($i = $childIndex; $i < sizeof($data); $i++)
        $this->traverseUnserializedData($data[$i], parent::__get("childNodes"));
    }

    public static function createFromRML($data) {
      $serializedString = serialize($data);
      $serializedString = "C:".strlen(__CLASS__).":\"".__CLASS__."\":".strlen($serializedString).":{".$serializedString."}";

      return unserialize($serializedString);
    }
  }

?>